package cn.itcast.n5_共享模型_内存;

import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 * Test05_$$$$$_volatile设计模式_犹豫模式保证方法只被调用一次
 * </p>
 *
 * @author flyduck
 * @since 2024/12/11
 */
@Slf4j(topic = "c.Test05_$$$$$_volatile设计模式_犹豫模式保证方法只被调用一次")
public class Test05_$$$$$_volatile设计模式_犹豫模式保证方法只被调用一次 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination3 twoPhaseTermination3 = new TwoPhaseTermination3();
        twoPhaseTermination3.start();
        twoPhaseTermination3.start();
    }
}

@Slf4j(topic = "c.TwoPhaseTermination3")
class TwoPhaseTermination3{

    private Thread monitor;

    private volatile boolean stop = false;

    //判断是否执行过start方法
    private volatile boolean starting = false;

    //启动监控线程
    public void start(){
        synchronized (this) {
            if (starting) {
                return;
            }
            starting = true;
        }
        monitor = new Thread(() -> {
            while (true) {
                if (stop) {
                    log.debug("料理后事");
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.debug("执行监控记录");
            }
        });
        monitor.start();
    }

    //停止监控线程
    public void stop(){
        stop = true;
    }

}
